package com.newtouch.cq.security.config.auth;

import cn.hutool.core.util.ArrayUtil;
import com.newtouch.cq.security.config.MccOauth2Properties;
import com.newtouch.cq.security.config.detail.CustomAuthenticationDetailsSource;
import com.newtouch.cq.security.config.handle.AuthenticationAccessDeniedHandler;
import com.newtouch.cq.security.config.handle.LoginSuccessHandle;
import com.newtouch.cq.security.config.handle.MyAuthenticationFailureHandler;
import com.newtouch.cq.security.util.CustomwordEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@Order(value = 20)
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfigration extends WebSecurityConfigurerAdapter {

    @Autowired
    private SecurityUserDetailsService userService;

    @Autowired
    private AuthenticationTokenFilter authenticationTokenFilter;

    @Autowired
    private CustomAuthenticationDetailsSource authenticationDetailsSource;

    @Autowired
    private LoginSuccessHandle loginSuccessHandle;

    @Autowired
    private MyAuthenticationFailureHandler myAuthenticationFailureHandler;

    @Autowired
    private AuthenticationAccessDeniedHandler authenticationAccessDeniedHandler;

    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
//        BCryptPasswordEncoder bcp = new BCryptPasswordEncoder();
//        auth
//                .inMemoryAuthentication().passwordEncoder(bcp).withUser("bill").password(bcp.encode("123")).roles("USER")
//                .and()
//                .withUser("admin").password(bcp.encode("123")).roles("ADMIN")
//                .and()
//                .withUser("dba").password(bcp.encode("123")).roles("ADMIN", "DBA");

        auth.userDetailsService(userService).passwordEncoder(new CustomwordEncoder());
    }

    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers("/favicon.ico", "/resources/**", "/error");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //是否禁用httpsession，根据配置定，默认禁用
        if(MccOauth2Properties.disableSession) {
           http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).disable();
        }
        if(MccOauth2Properties.authentication) {
            http.exceptionHandling().accessDeniedHandler(authenticationAccessDeniedHandler);
        }

        http
                .regexMatcher("/.+")
                .csrf().disable() //关闭csrf
                .formLogin()
                .loginPage("/auth/loginPage")
                .loginProcessingUrl("/auth/token")
                .successHandler(loginSuccessHandle)
//                .successForwardUrl("/auth/loginSuccess")
//                .defaultSuccessUrl("/auth/loginSuccess")
//                .failureUrl("/auth/failure")
                .failureHandler(myAuthenticationFailureHandler)
//                .failureForwardUrl("/auth/failure")
                .authenticationDetailsSource(authenticationDetailsSource)
                .permitAll()
//                .and()
//                .logout()
//                .logoutUrl("/auth/loginOut")
////                .logoutSuccessHandler(new ForwardLogoutSuccessHandler("/auth/loginOut"))
//                .logoutSuccessUrl("/auth/loginOutSuccess")
//                .permitAll()
                .and()
                // 授权配置
                .authorizeRequests()
                //所有静态文件可以访问
                .antMatchers("/js/**", "/css/**", "/images/**","/common/**").permitAll()
                .antMatchers(ArrayUtil.toArray(MccOauth2Properties.urlPermitAll,String.class)).permitAll()
                .anyRequest()         // 所有请求
//                .fullyAuthenticated()  //所有用户都可以放问
                .authenticated()
                .and()
                .addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class)
//                .exceptionHandling().accessDeniedHandler(authenticationAccessDeniedHandler)
        ;

    }



}
